package cn.com.bo.util.http;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

import org.apache.http.HttpEntity;  
import org.apache.http.HttpResponse;  
import org.apache.http.NameValuePair;  
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;  
import org.apache.http.client.entity.UrlEncodedFormEntity;  
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.message.BasicNameValuePair;  
import org.apache.http.util.EntityUtils; 


/**
 * 
 * @author Zhang Shaobo
 *
 */
public class HttpClientUtil {

	/**
	 * 
	* @Title: getPageContent
	* @Description: TODO(POST获取网页内容)
	* @param @param strUrl 请求URL，如：http://58.20.34.251:18080/index.php/xml/file/md5/campaigns
	* @param @param strPostRequest
	* @param @param maxLength 请求最大长度 100500
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public static String getPageContent(String strUrl, String strPostRequest,  
            int maxLength) {  
        // 读取结果网页  
        StringBuffer buffer = new StringBuffer();  
        System.setProperty("sun.net.client.defaultConnectTimeout", "5000");  
        System.setProperty("sun.net.client.defaultReadTimeout", "5000");  
        try {  
            URL newUrl = new URL(strUrl);  
            HttpURLConnection hConnect = (HttpURLConnection) newUrl  
                    .openConnection();  
            // POST方式的额外数据  
            if (strPostRequest.length() > 0) {  
                hConnect.setDoOutput(true);  
                OutputStreamWriter out = new OutputStreamWriter(hConnect  
                        .getOutputStream());  
                out.write(strPostRequest);  
                out.flush();  
                out.close();  
            }  
            // 读取内容  
              
            BufferedReader rd = new BufferedReader(new InputStreamReader(  
                    hConnect.getInputStream()));  
            int ch;  
            for (int length = 0; (ch = rd.read()) > -1  
                    && (maxLength <= 0 || length < maxLength); length++)  
                buffer.append((char) ch);  
            String s = buffer.toString();  
            s.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "");  
            System.out.println(s);  
              
            rd.close();  
            hConnect.disconnect();  
            return buffer.toString().trim();  
        } catch (Exception e) {  
            // return "错误:读取网页失败！";  
        	System.err.println("错误：读取网页失败");
        	e.printStackTrace();
            return null;  
        }  
    }  
	
	/**
	 * 
	* @Title: getPageContent
	* @Description: TODO(get的方式请求)
	* @param @param strUrl
	* @param @param maxLength
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public static String getPageContent(String strUrl,  
            int maxLength) {  
        // 读取结果网页  
        StringBuffer buffer = new StringBuffer();  
        System.setProperty("sun.net.client.defaultConnectTimeout", "5000");  
        System.setProperty("sun.net.client.defaultReadTimeout", "5000");  
        try {  
            URL newUrl = new URL(strUrl);  
            HttpURLConnection hConnect = (HttpURLConnection) newUrl  
                    .openConnection();  
            hConnect.setRequestMethod("GET");
            InputStream inStream = hConnect.getInputStream();    
            Scanner scanner = new Scanner(inStream, "UTF-8");
            String result = scanner.useDelimiter("\\A").next();
            System.out.println(result);  
            return result;
        } catch (Exception e) {  
            // return "错误:读取网页失败！";  
        	System.err.println("错误：读取网页失败");
        	e.printStackTrace();
            return null;  
        }  
    }  
	
	public static void getRemoteFile(String strUrl, String fileName) throws IOException{
		URL url = new URL(strUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		DataInputStream input = new DataInputStream(conn.getInputStream());
		DataOutputStream output = new DataOutputStream(new FileOutputStream(fileName));
		byte[] buffer = new byte[1024 * 8];
		int count = 0;
		while ((count = input.read(buffer)) > 0) {
		output.write(buffer, 0, count);
		}
		output.close();
		input.close();
	}
	public String doPost(String url,Map<String,String> map){  
		String charset = "UTF-8";
		return doPost(url,map,charset);
    }  
	
	public String doPost(String url,Map<String,String> map,String charset){  
        HttpClient httpClient = null;  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
            httpClient = HttpConnectionManager.getDefaultHttpClient();  
            httpPost = new HttpPost(url);  
            //设置参数  
            List<NameValuePair> list = new ArrayList<NameValuePair>();  
            Iterator iterator = map.entrySet().iterator();  
            while(iterator.hasNext()){  
                Entry<String,String> elem = (Entry<String, String>) iterator.next();  
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));  
            }  
            if(list.size() > 0){  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);  
                httpPost.setEntity(entity);  
            }  
            HttpResponse response = httpClient.execute(httpPost);  
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,charset);  
                }  
            }  
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        return result;  
    }  
	
	
	public String doGet(String url) throws ClientProtocolException, IOException{
		String charset = "UTF-8";
		return doGet(url,charset);
	}
	
	public String doGet(String url,String charset) throws ClientProtocolException, IOException {  
        String result = null;  
        HttpClient httpClient = HttpConnectionManager.getDefaultHttpClient();  
        HttpGet httpGet = new HttpGet(url);  
        HttpResponse response = httpClient.execute(httpGet);  
        if(response.getStatusLine().getStatusCode() == 200){
        	 if(response != null){  
                 HttpEntity resEntity = response.getEntity();  
                 if(resEntity != null){  
                     result = EntityUtils.toString(resEntity,charset);  
                 }  
             }  
        } else {
        	return "{'statusCode':"+response.getStatusLine().getStatusCode()+"}";
        }
        return result;  
    } 
	
	public static void main(String[] args) {
	}
	
}
